// ==UserScript==
// @name         steam仓库库存自动出售 - 增强版
// @namespace    http://tampermonkey.net/
// @version      2025-05-14
// @description  自动出售Steam仓库中的物品，支持自定义配置
// @author       You
// @match        https://steamcommunity.com/profiles/*/inventory*
// @match        https://steamcommunity.com/id/*/inventory*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=steamcommunity.com
// @grant        GM_setValue
// @grant        GM_getValue
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// ==/UserScript==

(function() {
    'use strict';

    // 配置选项
    const CONFIG = {
        // 起始物品位置
        startItemIndex: GM_getValue('startItemIndex', 1),
        // 最大处理物品数量
        maxItemsToProcess: GM_getValue('maxItemsToProcess', 25),
        // 默认出售价格（根据你的货币单位调整）
        defaultPrice: GM_getValue('defaultPrice', 0.2),
        // 基础等待时间（毫秒）
        baseDelay: GM_getValue('baseDelay', 200),
        // 每次操作增加的等待时间（毫秒）
        delayIncrement: GM_getValue('delayIncrement', 50),
        // 完成后是否刷新页面
        refreshAfterComplete: GM_getValue('refreshAfterComplete', true),
        // 目标游戏ID（可选，留空则处理所有游戏）
        targetAppId: GM_getValue('targetAppId', '')
    };

    // 当前处理的物品索引
    let currentItemIndex = CONFIG.startItemIndex;

    console.log(`开始自动出售，当前物品位置：${currentItemIndex}`);

    // 检查是否已达到最大处理数量
    if (currentItemIndex > CONFIG.maxItemsToProcess) {
        alert(`已达到最大处理数量 ${CONFIG.maxItemsToProcess}，脚本将重置计数。`);
        resetItemIndex();
        return;
    }

    // 异步等待函数
    function sleep(delay) {
        return new Promise(resolve => setTimeout(resolve, delay));
    }

    // 重置物品索引
    function resetItemIndex() {
        GM_setValue('startItemIndex', 1);
        currentItemIndex = 1;
    }

    // 更新物品索引
    function updateItemIndex() {
        currentItemIndex++;
        GM_setValue('startItemIndex', currentItemIndex);
    }

    // 创建自定义配置界面
    function createConfigUI() {
        const style = document.createElement('style');
        style.textContent = `
            .steam-auto-sell-config {
                position: fixed;
                top: 20px;
                right: 20px;
                background: #171a21;
                color: #c7d5e0;
                padding: 15px;
                border-radius: 5px;
                box-shadow: 0 0 15px rgba(0,0,0,0.5);
                z-index: 9999;
                max-width: 300px;
            }
            .steam-auto-sell-config h3 {
                margin-top: 0;
                color: #66c0f4;
            }
            .steam-auto-sell-config label {
                display: block;
                margin: 10px 0 5px;
            }
            .steam-auto-sell-config input, .steam-auto-sell-config select {
                width: 100%;
                padding: 5px;
                background: #2a2e38;
                color: #c7d5e0;
                border: 1px solid #444;
                border-radius: 3px;
            }
            .steam-auto-sell-config button {
                background: #5c7e10;
                color: #fff;
                border: none;
                padding: 8px 15px;
                margin-top: 10px;
                border-radius: 3px;
                cursor: pointer;
                width: 100%;
            }
            .steam-auto-sell-config button:hover {
                background: #6fa629;
            }
        `;
        document.head.appendChild(style);

        const configDiv = document.createElement('div');
        configDiv.className = 'steam-auto-sell-config';
        configDiv.innerHTML = `
            <h3>Steam自动出售配置</h3>
            <label>起始物品位置:</label>
            <input type="number" id="auto-sell-start-item-index" value="${CONFIG.startItemIndex}" min="1">

            <label>默认出售价格:</label>
            <input type="number" id="auto-sell-price" value="${CONFIG.defaultPrice}" step="0.01">

            <label>最大处理物品数:</label>
            <input type="number" id="auto-sell-max-items" value="${CONFIG.maxItemsToProcess}">

            <label>基础延迟(ms):</label>
            <input type="number" id="auto-sell-base-delay" value="${CONFIG.baseDelay}">

            <label>延迟增量(ms):</label>
            <input type="number" id="auto-sell-delay-inc" value="${CONFIG.delayIncrement}">

            <label>目标游戏ID:</label>
            <input type="text" id="auto-sell-appid" value="${CONFIG.targetAppId}" placeholder="留空处理所有游戏">

            <button id="save-auto-sell-config">保存配置</button>
            <button id="start-auto-sell">开始自动出售</button>
        `;
        document.body.appendChild(configDiv);

        // 保存配置
        document.getElementById('save-auto-sell-config').addEventListener('click', () => {
            const startIndex = parseInt(document.getElementById('auto-sell-start-item-index').value);
            const price = parseFloat(document.getElementById('auto-sell-price').value);
            const maxItems = parseInt(document.getElementById('auto-sell-max-items').value);
            const baseDelay = parseInt(document.getElementById('auto-sell-base-delay').value);
            const delayInc = parseInt(document.getElementById('auto-sell-delay-inc').value);
            const appId = document.getElementById('auto-sell-appid').value;

            GM_setValue('startItemIndex', startIndex);
            GM_setValue('defaultPrice', price);
            GM_setValue('maxItemsToProcess', maxItems);
            GM_setValue('baseDelay', baseDelay);
            GM_setValue('delayIncrement', delayInc);
            GM_setValue('targetAppId', appId);

            currentItemIndex = startIndex;
            alert('配置已保存！');
            location.reload();
        });

        // 手动启动出售
        document.getElementById('start-auto-sell').addEventListener('click', () => {
            GM_setValue('isSelling', true);
            startAutoSell();
        });
    }

    // 开始自动出售流程
    async function startAutoSell() {
        if (currentItemIndex > CONFIG.maxItemsToProcess) {
            alert(`已完成所有 ${CONFIG.maxItemsToProcess} 个物品的出售！`);
            resetItemIndex();
            GM_setValue('isSelling', false);
            return;
        }

        let currentDelay = CONFIG.baseDelay;
        let itemSelector;

        try {
            // 获取当前用户ID
            const userIdMatch = window.location.href.match(/(profiles|id)\/([^/]+)/);
            if (!userIdMatch) {
                console.error('无法识别用户ID');
                return;
            }

            const userId = userIdMatch[2];

            // 如果指定了游戏ID，则使用该游戏ID，否则尝试从URL获取
            let appId = CONFIG.targetAppId;
            if (!appId) {
                const appIdMatch = window.location.href.match(/app\/(\d+)/);
                appId = appIdMatch ? appIdMatch[1] : '';
            }

            // 构建物品选择器
            if (appId) {
                itemSelector = `#inventory_${userId}_${appId}_2 > div:nth-child(1) > div:nth-child(${currentItemIndex}) > div > a`;
            } else {
                // 如果没有指定游戏ID，尝试选择第一个可见的物品
                itemSelector = `#inventory_page_${currentItemIndex} .itemHolder`;
            }

            console.log('使用选择器:', itemSelector);

            // 步骤1: 选择物品
            await sleep(currentDelay);

            const itemElement = document.querySelector(itemSelector);
            if (!itemElement) {
                console.log(`未找到物品 ${currentItemIndex}，可能已处理完所有物品`);
                resetItemIndex();
                GM_setValue('isSelling', false);
                return;
            }

            // 高亮显示当前处理的物品
            itemElement.style.boxShadow = '0 0 10px yellow';

            // 点击物品
            itemElement.click();
            console.log(`已选择物品 ${currentItemIndex}`);
            currentDelay += CONFIG.delayIncrement;

            // 步骤2: 点击出售按钮
            await sleep(currentDelay);
            const sellButton = document.querySelector('#iteminfo1_item_market_actions > a > span.item_market_action_button_contents');
            if (!sellButton) {
                console.log(`物品 ${currentItemIndex} 不可出售，跳过`);
                updateItemIndex();
                window.location.reload();
                return;
            }

            sellButton.click();
            console.log('已点击出售按钮');
            currentDelay += CONFIG.delayIncrement;

            // 步骤3: 设置出售价格
            await sleep(currentDelay);
            const priceInput = document.querySelector('#market_sell_buyercurrency_input');
            if (priceInput) {
                // 使用模拟输入而不是直接赋值
                const priceText = CONFIG.defaultPrice.toString();
                simulateTyping(priceInput, priceText, 50);
                console.log(`已设置价格为 ${CONFIG.defaultPrice}`);
            } else {
                console.log('未找到价格输入框');
            }
            currentDelay += CONFIG.delayIncrement;

            // 步骤4: 聚焦货币输入框
            await sleep(currentDelay);
            const currencyInput = document.querySelector('#market_sell_currency_input');
            if (currencyInput) {
                currencyInput.click();
                console.log('已聚焦货币输入框');
            } else {
                console.log('未找到货币输入框');
            }
            currentDelay += CONFIG.delayIncrement;

            // 步骤5: 接受SSA
            await sleep(currentDelay);
            const acceptSsa = document.querySelector('#market_sell_dialog_accept_ssa');
            if (acceptSsa) {
                acceptSsa.click();
                console.log('已接受SSA');
            } else {
                console.log('未找到接受SSA按钮');
            }
            currentDelay += CONFIG.delayIncrement;

            // 步骤6: 确认出售
            await sleep(currentDelay);
            const confirmButton = document.querySelector('#market_sell_dialog_accept');
            if (confirmButton) {
                confirmButton.click();
                console.log('已点击确认出售');
            } else {
                console.log('未找到确认出售按钮');
            }
            currentDelay += CONFIG.delayIncrement;

            // 步骤7: 再次确认出售（如果需要）
            await sleep(currentDelay);
            const confirmButtonAgain = document.querySelector('#market_sell_dialog_accept');
            if (confirmButtonAgain) {
                confirmButtonAgain.click();
                console.log('再次点击确认出售');
            } else {
                console.log('不需要再次确认出售');
            }
            currentDelay += CONFIG.delayIncrement;

            // 步骤8: 点击完成
            await sleep(currentDelay);
            const finishButton = document.querySelector('#market_sell_dialog_ok');
            if (finishButton) {
                finishButton.click();
                console.log('已点击完成');
            } else {
                console.log('未找到完成按钮');
            }

            // 更新物品索引
            updateItemIndex();
            console.log(`已完成物品 ${currentItemIndex-1} 的出售，下一个处理: ${currentItemIndex}`);

            // 等待一段时间后刷新页面或继续处理下一个
            await sleep(1000);

            if (currentItemIndex > CONFIG.maxItemsToProcess) {
                alert(`已完成所有 ${CONFIG.maxItemsToProcess} 个物品的出售！`);
                resetItemIndex();
                GM_setValue('isSelling', false);
            } else {
                if (CONFIG.refreshAfterComplete) {
                    window.location.reload();
                } else {
                    // 继续处理下一个物品
                    startAutoSell();
                }
            }

        } catch (error) {
            console.error('执行过程中出现错误:', error);
            alert(`自动出售出错: ${error.message}`);
            GM_setValue('isSelling', false);
        }
    }

    // 模拟输入函数（从之前的脚本复用）
    function simulateTyping(element, text, delay) {
        let index = 0;

        // 创建输入事件
        const createEvent = (type) => {
            const event = new Event(type, {
                bubbles: true,
                cancelable: true,
            });
            return event;
        };

        // 输入单个字符
        const typeChar = () => {
            if (index < text.length) {
                const char = text[index];

                // 触发beforeinput事件
                const beforeInputEvent = createEvent('beforeinput');
                beforeInputEvent.data = char;
                element.dispatchEvent(beforeInputEvent);

                // 更新输入框值
                element.value += char;

                // 触发input事件
                const inputEvent = createEvent('input');
                element.dispatchEvent(inputEvent);

                // 触发keydown、keypress和keyup事件
                const keyEvents = ['keydown', 'keypress', 'keyup'];
                keyEvents.forEach(eventType => {
                    const event = new KeyboardEvent(eventType, {
                        bubbles: true,
                        cancelable: true,
                        key: char,
                        code: `Key${char.toUpperCase()}`,
                        keyCode: char.charCodeAt(0),
                        which: char.charCodeAt(0),
                    });
                    element.dispatchEvent(event);
                });

                // 设置光标位置到文本末尾
                element.selectionStart = element.selectionEnd = element.value.length;

                // 触发change事件
                if (index === text.length - 1) {
                    setTimeout(() => {
                        element.dispatchEvent(createEvent('change'));
                    }, 100);
                }

                index++;
                setTimeout(typeChar, delay);
            }
        };

        // 聚焦输入框
        element.focus();

        // 开始输入
        setTimeout(typeChar, delay);
    }

    // 创建配置界面
    createConfigUI();

    // 如果是自动运行模式或者之前已经开始出售，则开始自动出售
    if (GM_getValue('isSelling', false)) {
        setTimeout(startAutoSell, 2000);
    }
})();